import { onMounted, onUnmounted, type Ref } from 'vue'

function updateBBox(padding: number[], rect: { left: number; top: number }, bBox: number[]) {
  const cw = document.body.clientWidth
  const ch = document.body.clientHeight
  bBox[0] = padding[0] - rect.left //minX
  bBox[1] = padding[1] - rect.top //minY
  bBox[2] = cw - rect.left - padding[2] //maxX
  bBox[3] = ch - rect.top - padding[3] //maxY
}

function updateInitBBox(rect: { left: number; top: number }, bBox: number[], initBBox: number[]) {
  const cw = document.body.clientWidth

  let x0 = bBox[0]
  if (rect.left >= cw / 2) {
    x0 = cw / 2 - rect.left
    x0 = Math.max(bBox[0], x0)
    x0 = Math.min(bBox[2], x0)
  }
  const y0 = bBox[1]

  initBBox[0] = x0
  initBBox[1] = y0
  initBBox[2] = x0 + 100
  initBBox[3] = y0 + 100
  //todo check max x ,y
}

export function useFloatPaneBBox(props: { padding: number[] }, container: Ref<HTMLElement>) {
  const initBBox = [0, 0, 0, 0]
  const bBox = [0, 0, 0, 0]

  const initBBoxes = () => {
    const rect = container.value.getBoundingClientRect()
    updateBBox(props.padding, rect, bBox)
    updateInitBBox(rect, bBox, initBBox)
  }

  const onResize = () => {
    updateBBox(props.padding, container.value.getBoundingClientRect(), bBox)
  }

  onMounted(() => {
    initBBoxes()
    window.addEventListener('resize', onResize)
    // document.body.addEventListener('resize', onResize) //不生效
  })

  onUnmounted(() => {
    window.addEventListener('resize', onResize)
    // document.body.removeEventListener('resize', onResize)
  })

  return { initBBox, bBox }
}
